package com.shop.shopserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.shopcommon.exception.Base.PrivilegesNotFoundException;
import com.shop.shopcommon.token.CustomUser;
import com.shop.shoppojo.entity.User;
import com.shop.shopserver.mapper.UserMapper;
import com.shop.shopserver.service.PasswordUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.shop.shopcommon.constant.MessageConstant.PRIVILEGES_NOT_FOUND;
import static com.shop.shopcommon.constant.MessageConstant.USER_NOT_EXISTS;

/**
 * 自定义UserDetailsService用户登录认证
 * -用户密码认证
 */
//@Service
//@Slf4j
//public class PasswordUserDetailsServiceImpl implements PasswordUserDetailsService {
//    @Autowired
//    private UserMapper userMapper;
//    @Override
//    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        log.info("进入密码认证");
//        // 获取当前登录用户信息
//        LambdaQueryWrapper<User> userLambdaQueryWrapper = new QueryWrapper<User>().lambda();
//        userLambdaQueryWrapper.eq(User::getUsername, username)
//                .select(User::getId, User::getUsername, User::getPassword, User::getValid);
//        User user = userMapper.selectOne(userLambdaQueryWrapper);
//        if (user == null) {
//            //如果用户查不到，返回null，会抛出异常
//            throw new UsernameNotFoundException(USER_NOT_EXISTS +":" + username);
//        }
//        //根据用户id查询用户权限
//        List<String> privileges = userMapper.findPrivilegesByUserId(user.getId());
//        //将privileges转成数组
//        if (privileges == null|| privileges.isEmpty()){
//            throw new PrivilegesNotFoundException(PRIVILEGES_NOT_FOUND +":" + username);
//        }
//        String[] privilegeArray = new String[privileges.size()];
//        privileges.toArray(privilegeArray);
//        // 设置并返回UserDetails
//        UserDetails userDetails = org.springframework.security.core.userdetails.User
//                .withUsername(user.getUsername())
//                .password(user.getPassword())
//                .disabled(!user.getValid())
//                .authorities(privilegeArray).build();
//        log.info("userDetails = " + userDetails);
//        return userDetails;
//    }
//}

@Service
@Slf4j
public class PasswordUserDetailsServiceImpl implements PasswordUserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public CustomUser loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("进入密码认证");
        // 获取当前登录用户信息
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new QueryWrapper<User>().lambda();
        userLambdaQueryWrapper.eq(User::getUsername, username)
                .select(User::getId, User::getUsername, User::getPassword, User::getValid);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        if (user == null) {
            //如果用户查不到，返回null，会抛出异常
            throw new UsernameNotFoundException(USER_NOT_EXISTS +":" + username);
        }
        //根据用户id查询用户权限
        List<String> privileges = userMapper.findPrivilegesByUserId(user.getId());
        //将privileges转成数组
        if (privileges == null|| privileges.isEmpty()){
            throw new PrivilegesNotFoundException(PRIVILEGES_NOT_FOUND +":" + username);
        }
        String[] privilegeArray = new String[privileges.size()];
        privileges.toArray(privilegeArray);

        // 将权限列表转换为GrantedAuthority集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String privilege : privileges) {
            authorities.add(new SimpleGrantedAuthority(privilege));
        }
        // 设置并返回UserDetails
//        UserDetails userDetails = org.springframework.security.core.userdetails.User
//                .withUsername(user.getUsername())
//                .password(user.getPassword())
//                .disabled(!user.getValid())
//                .authorities(privilegeArray).build();
        // 返回自定义的UserDetails
        CustomUser userDetails = new CustomUser(user.getUsername(), user.getPassword(), true, true, true, true, authorities, user.getId());
        log.info("userDetails = " + userDetails);
        return userDetails;
    }
}

